package com.lzgang.ctrl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

@RestController
public class CtrlController {

    @Value("${shell-path}")
    private String shellPath;

    @Value("${shell-suffix}")
    private String shellSuffix;

    /**
     * 执行shell命令/脚本
     *
     * @param script
     * @param shellPath
     * @return
     */
    @GetMapping("execute")
    public String execute(@RequestParam String script, @RequestParam(required = false) String shellPath) {
        if (!StringUtils.hasText(shellPath)) shellPath = this.shellPath;
        /** 如果目录下有此脚本，执行脚本，否则作为一个命令执行 */
        return execute(new File(shellPath + script + this.shellSuffix).exists() ? shellPath + script + this.shellSuffix : script);
    }

    /**
     * 执行shell命令/脚本
     *
     * @param script
     * @return
     */
    private String execute(String script) {
        StringBuilder sb = new StringBuilder();
        try {
            Process child = Runtime.getRuntime().exec(script);
            InputStream in = child.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "gbk"));
            String line;
            while ((line = bufferedReader.readLine()) != null) sb.append(line + "\n");
            in.close();
            child.waitFor();
            return sb.length() > 0 ? sb.toString() : "success";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

}
